import { createRouter, createWebHistory } from "vue-router";
// import Layout from '@/components/Layout.vue'
import Login from "@/views/login/Login.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {
    //   path: '/',
    //   name: 'layout',
    //   component: Layout
    // },
    {
      path: "/login",
      name: "登录",
      component: Login,
    },
  ],
});

const views = import.meta.glob("../views/**/*.vue");
const homeView = import.meta.glob("../views/*.vue");
const loadView = Object.assign(views, homeView);
export const setRoutes = () => {
  //拼装动态路由
  const storeMenus = localStorage.getItem("menus");
  if (storeMenus) {
    const managerRote = {
      path: "/",
      name: "layout",
      component: () => import("../components/Layout"),
      redirect: "/home",
      children: [
        // {
        //   path: "person",
        //   name: "个人信息",
        //   component: () => import("../views/Personal Center/Person"),
        // },
        // {
        //   path: "updatePwd",
        //   name: "修改密码",
        //   component: () => import("../views/Personal Center/UpdatePwd"),
        // },
      ],
    };
    const menus = JSON.parse(storeMenus);
    menus.forEach((item) => {
      if (item.path) {
        //当前仅当path不为空的时候才去设置

        let itemMenu = {
          path: item.path.replace("/", ""),
          name: item.name,
          component:
            loadView[
              "../views" +
                (item.pagePath[0] === "/"
                  ? item.pagePath
                  : `/${item.pagePath}`) +
                ".vue"
            ],
        };
        managerRote.children.push(itemMenu);
      } else if (item.children.length) {
        item.children.forEach((item) => {
          if (item.path) {
            //当前仅当path不为空的时候才去设置

            let itemMenu = {
              path: item.path.replace("/", ""),
              name: item.name,
              component:
                loadView[
                  "../views" +
                    (item.pagePath[0] === "/"
                      ? item.pagePath
                      : `/${item.pagePath}`) +
                    ".vue"
                ],
            };
            managerRote.children.push(itemMenu);
          }
        });
      }
    });
    //动态添加到现在的路由对象去
    router.addRoute(managerRote);
  }
};

setRoutes();

router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name); //设置路由名称
  //store.commit("setPath")  //触发store的数据更新
  //未找到路由的情况
  // console.log(to.name, from.name)

  if (!to.matched.length) {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {
      next("/404");
    } else {
      //跳回登录页面
      next("/login");
    }
  }
  next(); //放行路由
});

export default router;
